package com.factory.rest.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.factory.common.pojo.Result;
import com.factory.common.utils.StringUtil;
import com.factory.rest.feign.AiClients;
import com.factory.rest.manager.WebRTCManager;
import com.factory.rest.spring.SpringCtxUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * webRTC控制器
 *
 * @author JW
 * @version 1.0
 * @date 2021/2/1 10:18
 */
@ServerEndpoint("/rest/webRTC/{id}")
@Controller
@Slf4j
@CrossOrigin
public class WebRTCController {

    private AiClients aiClients = SpringCtxUtils.getBean(AiClients.class);

    @OnOpen
    public void onOpen(Session session, @PathParam(value = "id") String id) {
        //获取连接的用户
        log.info("加入session:" + id);
        WebRTCManager.setSession(id, session);
    }

    @OnClose
    public void onClose(Session session) {
        log.info("移除不用的session:" + session.getId());
        WebRTCManager.closeSession(session);
    }


    //收到客户端信息
    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        log.info("message,{}", message);
        JSONObject jsonObject;

        try {
            jsonObject = JSON.parseObject(message);
        }catch (JSONException jsonException){
            log.error("格式化json错误!");
            return;
        }

        if (!jsonObject.containsKey("heart")){
            aiClients.webRtc(jsonObject);
//            WebRTCManager.sendMessage(jsonObject.getString("toUserId"), jsonObject.toJSONString());
        }
    }

    //错误时调用
    @OnError
    public void onError(Session session, Throwable throwable) {
        log.error("webSocket 错误,{}", throwable.getMessage());
        WebRTCManager.closeSession(session);
    }

}
